<template>
	<view class="container">
		<view class="login-card">
			<view class="card-header">
				<view class="home-link" @click="goHome">
					<text>← 返回首页</text>
				</view>
				<text class="welcome-text">登录</text>
			</view>
			
			<view class="form-item">
				<view class="input-wrapper">
					<text class="iconfont icon-user"></text>
					<input type="text" v-model="formData.account" placeholder="请输入账号" />
				</view>
				<text class="error-message" v-if="errors.account">{{ errors.account }}</text>
			</view>
			
			<view class="form-item">
				<view class="input-wrapper">
					<text class="iconfont icon-lock"></text>
					<input type="password" v-model="formData.password" placeholder="请输入密码" password />
				</view>
				<text class="error-message" v-if="errors.password">{{ errors.password }}</text>
			</view>
			
			<view class="form-item role-form-item">
				<text class="label">身份</text>
				<picker @change="handleRoleChange" :value="roleIndex" :range="roleLabels">
					<view class="picker">
						<text>{{ roleLabels[roleIndex] }}</text>
					</view>
				</picker>
			</view>
			
			<view class="button-group">
				<button type="primary" @click="handleLogin" class="login-btn">立即登录</button>
				<view class="register-link" @click="handleRegister">
					<text>还没有账号？立即注册</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import http, { SERVER_BASE_URL } from '@/utils/request';

export default {
	data() {
		return {
			formData: {
				account: '',
				password: ''
			},
			errors: {
				account: '',
				password: ''
			},
			// 角色选项
			roleOptions: [
				{ value: 'USER', label: '用户' },
				{ value: 'RIDER', label: '骑手' },
				{ value: 'ADMIN', label: '管理员' }
			],
			role: 'USER',
			roleIndex: 0
		};
	},
	computed: {
		roleLabels() {
			return this.roleOptions.map(option => option.label);
		}
	},
	methods: {
		// 去首页
		goHome() {
			uni.switchTab({
				url: '/pages/index/index'
			});
		},
		
		// 处理角色选择
		handleRoleChange(e) {
			const index = e.detail.value;
			this.roleIndex = index;
			this.role = this.roleOptions[index].value;
		},
		
		// 前往注册页面
		handleRegister() {
			uni.navigateTo({
				url: '/pages/register/register'
			});
		},
		
		// 验证表单
		validateForm() {
			let isValid = true;
			
			// 重置错误信息
			this.errors = {
				account: '',
				password: ''
			};
			
			// 验证账号
			if (!this.formData.account) {
				this.errors.account = '请输入账号';
				isValid = false;
			}
			
			// 验证密码
			if (!this.formData.password) {
				this.errors.password = '请输入密码';
				isValid = false;
			}
			
			return isValid;
		},
		
		// 登录
		async handleLogin() {
			// 验证表单
			if (!this.validateForm()) return;
			
			// 显示加载中
			uni.showLoading({
				title: '登录中...'
			});
			
			try {
				// 使用封装的http模块发送请求，但直接使用uni.request以获得完整响应
				const res = await new Promise((resolve, reject) => {
					uni.request({
						url: SERVER_BASE_URL + '/login',
						method: 'POST',
						data: {
							username: this.formData.account,
							password: this.formData.password,
							role: this.role
						},
						success: (response) => {
							console.log('登录响应:', response);
							resolve(response);
						},
						fail: (error) => {
							console.error('请求失败:', error);
							reject(error);
						}
					});
				});
				
				// 隐藏加载提示
				uni.hideLoading();
				
				// 处理返回结果
				if (res.statusCode === 200 && res.data.code === 200) {
					// 获取返回数据
					const responseData = res.data.data;
					// 提取用户信息和token
					const userInfo = responseData.userInfo;
					const token = responseData.token || '';
					
					console.log('登录成功:', responseData);
					console.log('用户信息:', userInfo);
					console.log('Token:', token);
					
					// 保存到本地存储
					uni.setStorageSync('user', JSON.stringify(userInfo));
					uni.setStorageSync('token', token);
					
					uni.showToast({
						title: '登录成功',
						icon: 'success'
					});
					
					// 根据角色跳转
					setTimeout(() => {
						if (userInfo.role === 'ADMIN') {
							uni.showToast({
								title: '管理员请使用Web端',
								icon: 'none'
							});
							// 管理员身份在小程序中仅作提示，不提供管理功能
							uni.switchTab({
								url: '/pages/user/user'
							});
						} else if (userInfo.role === 'RIDER') {
							// 骑手身份在小程序中暂不提供专门页面，转到用户页面
							uni.showToast({
								title: '骑手请使用Web端',
								icon: 'none'
							});
							uni.switchTab({
								url: '/pages/user/user'
							});
						} else {
							uni.switchTab({
								url: '/pages/user/user'
							});
						}
					}, 1500);
				} else {
					uni.showToast({
						title: res.data?.message || '登录失败',
						icon: 'none'
					});
				}
			} catch (error) {
				uni.hideLoading();
				uni.showToast({
					title: error.message || '登录失败，请检查网络',
					icon: 'none'
				});
				console.error('登录请求失败:', error);
			}
		}
	}
};
</script>

<style>
.container {
	padding: 30rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.login-card {
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 40rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.card-header {
	position: relative;
	text-align: center;
	margin-bottom: 50rpx;
	padding-top: 20rpx;
}

.home-link {
	position: absolute;
	left: 0;
	top: 0;
	font-size: 28rpx;
	color: #409EFF;
}

.welcome-text {
	font-size: 48rpx;
	font-weight: bold;
}

.form-item {
	margin-bottom: 40rpx;
}

.input-wrapper {
	display: flex;
	align-items: center;
	height: 90rpx;
	padding: 0 30rpx;
	background-color: #f5f5f5;
	border-radius: 45rpx;
}

.input-wrapper input {
	flex: 1;
	height: 90rpx;
	font-size: 30rpx;
}

.iconfont {
	font-size: 40rpx;
	color: #999;
	margin-right: 20rpx;
}

.error-message {
	color: #F56C6C;
	font-size: 24rpx;
	margin-top: 10rpx;
	padding-left: 20rpx;
}

.role-form-item {
	display: flex;
	align-items: center;
}

.label {
	font-size: 30rpx;
	color: #333;
	margin-right: 20rpx;
	width: 100rpx;
}

.picker {
	flex: 1;
	height: 90rpx;
	background-color: #f5f5f5;
	border-radius: 45rpx;
	padding: 0 30rpx;
	display: flex;
	align-items: center;
}

.button-group {
	margin-top: 60rpx;
	display: flex;
	flex-direction: column;
	gap: 30rpx;
}

.login-btn {
	width: 100%;
	height: 90rpx;
	border-radius: 45rpx;
	font-size: 32rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.register-link {
	text-align: center;
	font-size: 28rpx;
	color: #409EFF;
	padding: 20rpx;
}
</style> 